package com.hrpc.config;

import com.caucho.hessian.io.Serializer;
import com.hrpc.compress.Compressor;
import com.hrpc.compress.CompressorFactory;
import com.hrpc.loadbalancer.LoadBalancer;
import com.hrpc.serialize.Serialize;
import com.hrpc.serialize.SerializeFactory;
import com.hrpc.spi.SpiHandler;

import java.util.List;

public class SpiReslover {
    /**
     * 通过Spi的方式加载配置项
     * @param configuration
     */
    public void loadFromSpi(Configuration configuration) {
        //我的Spi文件中配置了很多文件（自由定义，只能配置一个实现还是多个）
        List<ObjectWrapper<LoadBalancer>> loadBalancerWrappers = SpiHandler.getList(LoadBalancer.class);
        //将其放进工厂中
        if (loadBalancerWrappers!=null && loadBalancerWrappers.size()>0){
            configuration.setLoad_balancer(loadBalancerWrappers.get(0).getImpl());
        }
        List<ObjectWrapper<Compressor>> compressorList = SpiHandler.getList(Compressor.class);
        if(compressorList!=null){
            compressorList.forEach(objectWrapper -> {
                CompressorFactory.addCompressor(objectWrapper);
            });
        }
        List<ObjectWrapper<Serialize>> serializeList = SpiHandler.getList(Serialize.class);
        if(serializeList!=null){
            serializeList.forEach(objectWrapper -> {
                SerializeFactory.addSerializer(objectWrapper);
            });
        }

//        LoadBalancer loadBalancer= SpiHandler.get(LoadBalancer.class);
//        if (loadBalancer != null){
//            configuration.setLoad_balancer(loadBalancer);
//        }
//        Compressor compressor=SpiHandler.get(Compressor.class);
//        if (compressor != null){
//            configuration.setCompressor(compressor);
//        }
//        Serialize serializer=SpiHandler.get(Serialize.class);
//        if (serializer!=null){
//            configuration.setSerializer(serializer);
//        }

    }
}
